'use strict';
const dayjs = require("dayjs");
const {getDefaultModelConfig} = require("../../utils/common");

module.exports = app => {
    const { STRING, INTEGER, BIGINT, TINYINT, DECIMAL, TEXT } = app.Sequelize;
    const Product = app.model.define(
        'Product',
        {
            id: {type: INTEGER, primaryKey: true, autoIncrement: true},
            name: {type: STRING(255), allowNull: false, comment: '商品名称'},
            cover: {type: STRING(500), comment: '商品封面图片'},
            images: {type: TEXT, comment: '商品轮播图，JSON格式存储'},
            description: {type: TEXT, comment: '商品详情'},
            category_id: {type: INTEGER, comment: '商品分类ID'},
            sort: {type: INTEGER, defaultValue: 0, comment: '排序'},
            status: {type: TINYINT, defaultValue: 1, comment: '状态：1-上架，0-下架'},
            is_virtual: {type: TINYINT, defaultValue: 0, comment: '是否虚拟商品：1-是，0-否'},
            sales: {type: BIGINT, defaultValue: 0, comment: '销售数量'},
            ...getDefaultModelConfig(app)
        },
        {
            tableName: 'product',
            timestamps: true,
            createdAt: 'create_time',
            updatedAt: 'update_time'
        }
    );
    Product.associate = function() {
        Product.hasMany(app.model.Business.ProductSpec, { foreignKey: 'product_id', sourceKey: 'id', as: 'specs' });
        // sku 关联 product
        Product.hasMany(app.model.Business.ProductSku, { foreignKey: 'product_id', sourceKey: 'id', as: 'skus' });
        // 关联产品分类
        Product.belongsTo(app.model.Business.ProductCategory, { foreignKey: 'category_id', targetKey: 'id', as: 'category' });
    };
    return Product;
};
